import React, { useState } from 'react';
import { makeStyles, withStyles } from '@material-ui/core/styles';
import { Typography, Grid, Button, TextField } from '@material-ui/core';
import validate from 'validate.js';
import { LearnMoreLink } from 'components/atoms';
import { setProfile } from 'redux/actions/AuthActions'
import { useSelector, useDispatch } from 'react-redux'
import ReactHtmlParser from 'react-html-parser';
import { useHistory, useLocation } from "react-router-dom";
import { callPostApi } from 'utils/networking';

const useStyles = makeStyles(theme => ({
  root: {
    width: '100%',
  },
}));

const schema = {
  phone: {
    presence: { allowEmpty: false, message: 'is required' },
    length: {
      maximum: 20,
    },
  },
  code: {
    presence: { allowEmpty: false, message: 'is required' },
    length: {
      minimum: 6,
    },
  },
};

const RedTextTypography = withStyles({
  root: {
    color: "#FF0000",
    marginBottom: '20px'
  }
})(Typography);

let count = 0;
const Form = (props) => {

  const classes = useStyles();
  const preAuthPath = useSelector((state) => state.auth.preAuthPath);
  const [callbackError, setCallbackError] = React.useState('');
  const [resendable, setResendable] = useState(false)
  const [timeLabel, setTimeLabel] = useState('')

  let mInterval = null;

  const [formState, setFormState] = React.useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
  });

  React.useEffect(() => {
    const errors = validate(formState.values, schema);
    console.log('errors', errors)
    setFormState(formState => ({
      ...formState,
      isValid: errors ? false : true,
      errors: errors || {},
    }));
  }, [formState.values]);

  const stopTimer = () => {
    if (mInterval) {
      clearInterval(mInterval);
      mInterval = null;
    }
  }

  const startTimer = () => {
    setResendable(false)
    count = 150

    mInterval = setInterval(function () {
      count--;
      if (count === 0) {
        stopTimer()
        setResendable(true)
        setTimeLabel('')
      }
      else {
        const mins = Math.floor(count / 60)
        if (mins > 0) {
          const seconds = count - 60 * mins
          setTimeLabel(`${mins} mins ${seconds} secs`)
        }
        else {
          setTimeLabel(`${count} secs`)
        }
      }
    }, 1000);
  }

  const sendCode = () => {
    if (!formState.values.phone) {
      return;
    }

    const param = {
      phone: formState.values.phone,
    }
    callPostApi('user/send_verify_code', param, dispatch, (data) => {
      startTimer();
      
    }, (err) => {
      setCallbackError(err)
    })
  }

  const handleChange = event => {
    event.persist();

    console.log('count', count)
    if (formState.values.phone && formState.values.phone.length >= 8 && count === 0) {
      setResendable(true)
    }
    else {
      setResendable(false)
    }
 
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [event.target.name]:
          event.target.type === 'checkbox'
            ? event.target.checked
            : event.target.value,
      },
      touched: {
        ...formState.touched,
        [event.target.name]: true,
      },
    }));
  };

  const dispatch = useDispatch()
  let history = useHistory();

  const handleSubmit = event => {
    event.preventDefault();

    if (formState.isValid) {
      const param = {
        phone: formState.values.phone,
        code: formState.values.code
      }
      callPostApi('user/update_phone', param, dispatch, (data) => {
        history.replace("")
        
      }, (err) => {
        setCallbackError(err)
      })
    }

    setFormState(formState => ({
      ...formState,
      touched: {
        ...formState.touched,
        ...formState.errors,
      },
    }));
  };

  const hasError = field =>
    formState.touched[field] && formState.errors[field] ? true : false;

  return (
    <div className={classes.root}>
      {(
        <Grid item xs={12}>
          <RedTextTypography
            align="center"
            className={classes.errorLabel}
          >
            {ReactHtmlParser(callbackError)}
          </RedTextTypography>
        </Grid>
      )}
      <form name="password-reset-form" method="post" onSubmit={handleSubmit}>
        <Grid container spacing={2}>
          <Grid item xs={12}>
            <TextField
              placeholder="Input your phone number"
              label="Phone Number *"
              variant="outlined"
              size="medium"
              name="phone"
              fullWidth
              helperText={hasError('phone') ? formState.errors.phone[0] : null}
              error={hasError('phone')}
              onChange={handleChange}
              type="phone"
              value={formState.values.phone || ''}
            />
          </Grid>
          <Grid item xs={8}>
            <TextField
              placeholder="Input verify code"
              label="Verify Code *"
              variant="outlined"
              size="medium"
              name="code"
              fullWidth
              helperText={
                hasError('code') ? formState.errors.code[0] : null
              }
              error={hasError('code')}
              onChange={handleChange}
              type="code"
              value={formState.values.code || ''}
            />
          </Grid>
          <Grid item xs={4}>
            <Button
              size="small"
              variant="contained"
              color="primary"
              fullWidth
              disabled={!resendable}
              onClick={sendCode}
            >
              Send Code
            </Button>
            {timeLabel}
          </Grid>
          <Grid item xs={12}>
            <i>
              <Typography variant="subtitle2">
                Fields that are marked with * sign are required.
              </Typography>
            </i>
          </Grid>
          <Grid item xs={12}>
            <Button
              size="large"
              variant="contained"
              type="submit"
              color="primary"
              fullWidth
            >
              Submit
            </Button>
          </Grid>
        </Grid>
      </form>
    </div>
  );
};

export default Form;
